"""
健康检查路由
"""

from fastapi import APIRouter
from ..models import HealthResponse, BaseResponse
from ..logger import logger
from ..config import config
import time

router = APIRouter()


@router.get("/health", response_model=HealthResponse)
async def health_check():
    """健康检查端点"""
    try:
        # 检查各个服务状态
        services = {}
        
        # 检查存储服务
        try:
            from ..storage import data_manager
            await data_manager.get_models()
            services["storage"] = "healthy"
        except Exception as e:
            logger.error(f"Storage health check failed: {e}")
            services["storage"] = "unhealthy"
        
        # 检查配置服务
        try:
            config.get_server_config()
            services["config"] = "healthy"
        except Exception as e:
            logger.error(f"Config health check failed: {e}")
            services["config"] = "unhealthy"
        
        # 检查日志服务
        try:
            logger.info("Health check log test")
            services["logging"] = "healthy"
        except Exception as e:
            services["logging"] = "unhealthy"
        
        # 确定整体状态
        overall_status = "healthy" if all(
            status == "healthy" for status in services.values()
        ) else "degraded"
        
        return HealthResponse(
            status=overall_status,
            version="1.0.0",
            timestamp=time.time(),
            services=services
        )
        
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return HealthResponse(
            status="unhealthy",
            services={"error": str(e)}
        )


@router.get("/ping", response_model=BaseResponse)
async def ping():
    """简单的ping端点"""
    return BaseResponse(message="pong")


@router.get("/status", response_model=HealthResponse)
async def health_status():
    """健康状态端点（别名）"""
    return await health_check()


@router.get("/version", response_model=dict)
async def get_version():
    """获取版本信息"""
    return {
        "version": "1.0.0",
        "api_version": config.get('api.version', 'v1'),
        "build_time": "2024-01-01T00:00:00Z",
        "git_commit": "unknown"
    }
